package v1

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"zimuzu_cvn_web_api/config"
	. "zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
	"zimuzu_cvn_web_api/router/api"
	"zimuzu_cvn_web_api/router/api/admin/middleware"
	"zimuzu_cvn_web_api/service"
)

type UserAPI struct {
}

func (user UserAPI) Name() string {
	return "user API"
}

func (user UserAPI) Bind() {
	userAPI := config.C.Router.Group("/v1/admin", middleware.TrackLog(), middleware.AuthMiddleware())
	{
		userAPI.GET("adminuserList", adminuserList)
		userAPI.POST("adminuserDelete", adminuserDelete)
		userAPI.POST("adminuserAdd", adminuserAdd)

	}
}

type addParams struct {
	Phone string `form:"phone" json:"phone" binding:"required"`
	Password     string `form:"password" json:"password" binding:"required"`
	Nickname     string `form:"nickname" json:"nickname" binding:"required"`
}

//添加管理员
//Auth: Xu
func adminuserAdd(c *gin.Context) {
	var params addParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	uid, _ := service.GetUserIdByRequest(c)
	adminuser,err := service.GetAdminUserByUid(uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	if adminuser.Type != 1{
		api.SendResponse(c, errors.New("权限不足"), nil)
		return
	}

	if !IsPhone(params.Phone) {
		api.SendResponse(c, errors.New("请输入正确格式的手机号"), nil)
		return
	}

	_, errCreate := service.AddAdminUser(params.Phone, params.Password, params.Nickname)
	if errCreate != nil {
		api.SendResponse(c, errCreate, nil)
		return
	}

	errno.OK.Info = "添加成功"
	api.SendResponse(c, errno.OK, nil)
	return
}

//管理员列表
//Auth:Xu
func adminuserList(c *gin.Context){
	list, errCreate := service.AdminList()
	if errCreate != nil {
		api.SendResponse(c, errCreate, nil)
		return
	}

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, list)
	return
}

type deleteParams struct {
	Id int64 `form:"id" json:"id" binding:"required"`
}

//删除管理员
//Auth: Xu
func adminuserDelete(c *gin.Context) {
	var params deleteParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	adminuser,err := service.GetAdminUserByUid(uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	if adminuser.Type != 1{
		api.SendResponse(c, errors.New("权限不足"), nil)
		return
	}

	errDelete := service.DeleteAdminUser(params.Id)
	if errDelete != nil {
		api.SendResponse(c, errDelete, nil)
		return
	}

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, nil)
	return
}
